package com.an.framework.security.user;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.an.framework.security.user.dao.AuthorityDao;
import com.an.framework.security.user.service.UserService;
import com.an.framework.security.user.vo.Authority;
import com.an.framework.security.user.vo.User;

/**
 * ClassName: MyUserDetailServices <br/>
 * Function: 用户service. <br/>
 * Reason: 用户service. <br/>
 * date: 2017年11月8日 下午3:52:37 <br/>
 *
 * @author atc
 * @version 1.0.0
 * @since JDK 1.8
 */
@Service("nameddddddd")
public class MyUserDetailServices implements  UserDetailsService {

	private static final Logger log = LoggerFactory.getLogger(MyUserDetailServices.class);
	
	/**
	 * userService:用户表接口.
	 * @since JDK 1.8
	 */
	@Autowired
	private UserService userService;
	
	/**
	 * authorityDao:用户权限接口.
	 * @since JDK 1.8
	 */
	@Autowired
	private AuthorityDao authorityDao;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = null;
		log.debug("用户认证开始！！！！！！！！！！！！！");
		if(username == null || username.length() == 0) {
			log.info("用户名长度：username.length()=" + username.length());
			log.info("用户名为空，登录失败！！");
			throw new UsernameNotFoundException("username为空");
		}
		user = userService.getUserByUsername(username);
		if(null != user) {
			log.debug("用户名" + username + "存在数据。具体：" + user);
			log.debug("查询用户具有的权限列表");
			List<Authority> authorities = authorityDao.getAllauthorityByUsername(username);
			user.setAuthorities(authorities);
			log.debug("用户权限列表：" + authorities);
			return user;
		}
		log.debug("用户" + username + "不存在");
		throw new UsernameNotFoundException("用户名无对应信息");
	}

}
